package cn.sgy.infrastructure.web.req;

import cn.hutool.core.lang.UUID;
import org.slf4j.MDC;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * @author sgy
 * @description 负责生成起唯一请求ID的Filter
 * @date 2024/9/29
 */
public class ReqIdFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            String requestId = UUID.fastUUID().toString(true);
            MDC.put("requestId", requestId);
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            MDC.clear();
        }
    }
}
